package com.qf.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.StringUtils;
import com.qf.entity.Blogs;
import com.qf.entity.BlogsDTO;
import com.qf.service.BlogsService;
import com.qf.util.AliyunOSSUtil;
import com.qf.util.R;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

import java.util.List;

/**
 * @ClassName: UploadController
 * @Author: WangHao
 * @Date: 2025/4/29 19:12
 * @Description: OSS文件上传测试API
 * @Version: 1.0
 */
@RestController
@RequestMapping("/picture")
public class UploadController {
    /**
     * 演示上传文件到OSS
     */
@Autowired
private BlogsService blogsService;
    @PostMapping("/upload")
    public R upload(MultipartFile file){
        String filePath = AliyunOSSUtil.upLoad(file);
        return R.ok(filePath);
    }

    @GetMapping("/download/excel")
    public void export(HttpServletResponse response,
                       @RequestParam(required = false) String title) throws IOException {
        // 根据条件查询数据
        List<Blogs> list;
        if (StringUtils.isEmpty(title)) {  //StringUtils.isNotEmpty 有问题
            BlogsDTO dto = new BlogsDTO();
            dto.setTitle(title);
            list = blogsService.findPage(dto);
        } else {
            list = blogsService.findAll();
        }

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("博客数据", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 写入Excel
        EasyExcel.write(response.getOutputStream(), Blogs.class)
                .sheet("博客数据")
                .doWrite(list);
    }
}
